const shell=require('shelljs')
const path=require('path')
const fs= require('fs')
const iconv = require('iconv-lite')
const cliPath='E:/programefiles/HBuilderX/cli.exe'
const outDir=path.resolve(__dirname,'../unpackage/release')
const clear=false
const apps=[
	{
		configPath:path.resolve(__dirname,'./packs/street.json'),
		format:'cwstreet_{versionName}_{versionCode}_{channel}_{date}.apk',
		name:'潮玩街区',
		key:'isStreet',
		isPack:false,
		appId:'__UNI__0B040CE'
	},
	{
		configPath:path.resolve(__dirname,'./packs/magic.json'),
		format:'cwmagic_{versionName}_{versionCode}_{channel}_{date}.apk',
		name:'魔盒部落',
		key:'isMagic',
		isPack:true,
		appId:'__UNI__DE283F6'
	},
]
if(clear){
	shell.rm('-rf', `${outDir}/*`);
}
//shell.exec(`chcp 65001`)
if(!shell.which(cliPath)){
  shell.echo('Sorry, this script requires HBuilderX->cli.exe');
  shell.exit(1);
}
let time=(new Date()).getTime()
const appArr=apps.filter(item => item.isPack)
const configPath = path.resolve(__dirname,'../vue.config.js')
let config = fs.readFileSync(configPath, { encoding: 'utf-8' })
appArr.map((item,idx) =>{
	apps.map(item1 =>{
		config=config.replace(new RegExp(`${item1.key}=(?:true|false)`),`${item1.key}=false`)
	})
	config=config.replace(new RegExp(`${item.key}=(?:true|false)`),`${item.key}=true`)
	fs.writeFileSync(configPath,config, {
	  "flag": "w"
	})
	fs.access(item.configPath, fs.constants.F_OK, (err) => {
		if(err){
			shell.echo(`${item.configPath} 'does not exist'`)
			shell.exit(2);
		}
		generateApp(item.configPath,item.appId)
		setTimeout(() =>{
			renameApp(item.format)
		}, 10000)
	})
})

function generateApp(configPath,appid){
	const manifestPath = path.resolve(__dirname,'../manifest.json')
	let Manifest = fs.readFileSync(manifestPath, { encoding: 'utf-8' })
	const manifObj=JSON.parse(Manifest)
	manifObj['appid']=appid
	fs.writeFileSync(manifestPath,JSON.stringify(manifObj,null,4), {
	  "flag": "w"
	})
	const cliExec = shell.exec(`${cliPath} pack --config ${configPath}`, {async:false,encoding:'buffer',silent:true});
	time=(new Date()).getTime()
	const err=iconv.decode(cliExec.stderr, 'gb2312')
	const out=iconv.decode(cliExec.stdout, 'gb2312')
	console.log(out)
}
function renameApp(format){
	const manifestPath = path.resolve(__dirname,'../manifest.json')
	let Manifest = fs.readFileSync(manifestPath, { encoding: 'utf-8' })
	const manifObj=JSON.parse(Manifest);
	const files=fs.readdirSync(outDir)
	console.log('========================================')
	files.map(name =>{
		const stat=fs.statSync(`${outDir}/${name}`)
		if(time>stat.birthtimeMs) return
		const match=name.match(new RegExp(`^${manifObj.appid}_(.*)_(\\d{10})\\.apk$`))
		if(!match) return
		const cStr=timeFormat(stat.birthtimeMs,'yyyymmddhhMM')
		let newName=format
		newName=newName.replace('{appId}',manifObj.appid)
		newName=newName.replace('{versionName}',manifObj.versionName)
		newName=newName.replace('{versionCode}',manifObj.versionCode)
		newName=newName.replace('{date}',cStr)
		newName=newName.replace('{channel}',match[1])
		shell.mv(`${outDir}/${name}`, `${outDir}/${newName}`);
		console.log(`rename: ${name} to ${newName}`)
	})
	console.log('========================================')
}
function timeFormat(dateTime = null, fmt = 'yyyy-mm-dd') {
	if (!dateTime) dateTime = Number(new Date())
	if (dateTime.toString().length == 10) dateTime *= 1000
	const date = new Date(dateTime)
	let ret
	const opt = {
		'y+': date.getFullYear().toString(), // 年
		'm+': (date.getMonth() + 1).toString(), // 月
		'd+': date.getDate().toString(), // 日
		'h+': date.getHours().toString(), // 时
		'M+': date.getMinutes().toString(), // 分
		's+': date.getSeconds().toString() // 秒
	}
	for (const k in opt) {
		ret = new RegExp(`(${k})`).exec(fmt)
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
		}
	}
	return fmt
}